package com.wy.component.security;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

/**
 * java验证AD域用户登录 传入用户名(userName)和密码(password)进行验证，验证成功返回用户名
 * 
 * @author guob
 * 
 */
public class ADTest {

	public static String check(String userName, String password) {
		String host = "192.168.1.12"; // AD服务器IP（一共2个AD域服务器，备份的效果，另一个是10.156.129.95）
		String port = "389"; // 端口
		userName = userName + "@shwally.com";

		String url = new String("ldap://" + host + ":" + port);
		// String url = new String("ldap://mail/shwally.com");

		Hashtable env = new Hashtable();
		DirContext ctx;
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		// env.put(Context.SECURITY_AUTHENTICATION, "none");
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.PROVIDER_URL, url);
		// env.put(Context.SECURITY_PRINCIPAL, DN_CN+","+DN_OU);
		env.put(Context.SECURITY_PRINCIPAL, userName);
		env.put(Context.SECURITY_CREDENTIALS, password);

		try {
			ctx = new InitialDirContext(env);// 初始化上下文
			System.out.println("认证成功");

			ctx.close();
			return userName; // 验证成功返回name
		} catch (javax.naming.AuthenticationException e) {
			System.out.println("认证失败");
			System.out.println("e.getExplanation():" + e.getExplanation());
			System.out.println("e.getMessage():" + e.getMessage());
			return "";
		} catch (Exception e) {
			System.out.println("认证出错：" + e);
			return "";
		}
	}

}